package com.zjzywl.smoke.controller;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.List;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestClientException;
import org.springframework.web.multipart.MultipartFile;

import com.zjzywl.smoke.config.AppConfig;
import com.zjzywl.smoke.entity.Device;
import com.zjzywl.smoke.entity.FireBrigadePatrolRecord;
import com.zjzywl.smoke.entity.ZyStreet;
import com.zjzywl.smoke.util.RestResult;
import com.zjzywl.smoke.util.WebResult;

/*
 * 消防联队队伍巡查记录
 */
@Controller
@RequestMapping(value = "/fireBrigadePatrolRecord")
public class FireBrigadePatrolRecordController extends BaseController {
    // 同步锁对象
    Object obj = new Object();
    @Autowired
    private AppConfig appConfig;

    /*
     * 新建消防联队队伍巡查记录
     */
    @PostMapping(value = "/postSave")
    @ResponseBody
    public WebResult postSave(FireBrigadePatrolRecord fbr, MultipartFile namePhoto) throws Exception {
        // 存储签名照片
        FireBrigadePatrolRecord fbr1 = executeUpload(fbr, namePhoto);
        ResponseEntity<FireBrigadePatrolRecord> fireBrigadePatrolRecord = appConfig.restTemplate().postForEntity(
                appConfig.getGetDataIp() + "/fireBrigadePatrolRecord/save", fbr1, FireBrigadePatrolRecord.class);
        return WebResult.OK(fireBrigadePatrolRecord);
    }

    /*
     * 存储消防联队队伍巡查记录图片
     */
    @PostMapping(value = "/savePhoto")
    @ResponseBody
    public WebResult savePhoto(@RequestParam("id") Integer id, MultipartFile photo) throws Exception {
        while (true) {
            synchronized (obj) {
                // 存储消防联队队伍巡查记录图片
                String photoUrl = executeUploads(photo);
                ResponseEntity<FireBrigadePatrolRecord> fireBrigadePatrolRecord = appConfig.restTemplate()
                        .getForEntity(appConfig.getGetDataIp() + "/fireBrigadePatrolRecord/savePhoto?id=" + id
                                + "&photoUrl=" + photoUrl, FireBrigadePatrolRecord.class);
                return WebResult.OK(fireBrigadePatrolRecord);
            }
        }
    }

    /*
     * 查询巡检记录
     */
    @GetMapping(value = "/getList")
    @ResponseBody
    public WebResult getList(HttpServletRequest request) throws Exception {
        System.out.println(appConfig.getGetDataIp() + "/fireBrigadePatrolRecord/getList" + "?"
                + URLDecoder.decode(request.getQueryString(), "utf-8"));
        ResponseEntity<Object> fireBrigadePatrolRecord = appConfig.restTemplate().getForEntity(appConfig.getGetDataIp()
                + "/fireBrigadePatrolRecord/getList" + "?" + URLDecoder.decode(request.getQueryString(), "utf-8"),
                Object.class);
        return WebResult.OK(fireBrigadePatrolRecord);
    }

    /*
     * 模糊查询店铺名称和巡检人
     */
    @GetMapping(value = "/getLikeShopNameAndFirSafetyOfficer")
    @ResponseBody
    public WebResult getLikeShopNameAndFirSafetyOfficer(HttpServletRequest request)
            throws RestClientException, UnsupportedEncodingException {
        ResponseEntity<String[]> result = appConfig.restTemplate()
                .getForEntity(appConfig.getGetDataIp() + "/fireBrigadePatrolRecord/getLikeShopNameAndFirSafetyOfficer"
                        + "?" + URLDecoder.decode(request.getQueryString(), "utf-8"), String[].class);
        return WebResult.OK(result);
    }

    /*
     * 图片上传方法
     * 
     */
    private String executeUploads(MultipartFile photo) throws Exception {
        String uploadDir = getUploadDir() + "fbp" + "/";
        // 如果文件不存在，自动创建文件夹
        File dir = new File(uploadDir);
        if (!dir.exists()) {
            if (!dir.mkdirs()) {
                logger.error("创建上传目录失败");
            }
        }

        // 文件后缀名
        String suffix = photo.getOriginalFilename().substring(photo.getOriginalFilename().lastIndexOf("."));
        // 上传文件名
        String filename = UUID.randomUUID() + suffix;
        // 服务器端保存的文件对象
        File serverFile = new File(uploadDir + filename);
        // 将上传到的文件写入到服务器
        photo.transferTo(serverFile);
        // fbr.setNamePhotoUrl("/upload/" + deviceTypeId + "/" + filename);
        String url = "/upload/fbp/" + filename;

        return url;
    }

    /*
     * 图片上传方法
     * 
     */
    private FireBrigadePatrolRecord executeUpload(FireBrigadePatrolRecord fbr, MultipartFile file) throws Exception {
        String uploadDir = getUploadDir() + "autographPhoto" + "/";
        // 如果文件不存在，自动创建文件夹
        File dir = new File(uploadDir);
        if (!dir.exists()) {
            if (!dir.mkdirs()) {
                logger.error("创建上传目录失败");
            }
        }
        if (file != null) {
            // 文件后缀名
            String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
            // 上传文件名
            String filename = UUID.randomUUID() + suffix;
            // 服务器端保存的文件对象
            File serverFile = new File(uploadDir + filename);
            // 将上传到的文件写入到服务器
            file.transferTo(serverFile);
            // fbr.setNamePhotoUrl("/upload/" + deviceTypeId + "/" + filename);
            fbr.setNamePhotoUrl("/upload/autographPhoto/" + filename);
        }
        return fbr;
    }

    /*
     * 获取紫阳街道字典
     */
    @GetMapping(value = "/getStreet")
    @ResponseBody
    public WebResult getStreet() {
        ResponseEntity<ZyStreet[]> result = appConfig.restTemplate()
                .getForEntity(appConfig.getGetDataIp() + "/fireBrigadePatrolRecord/getStreet", ZyStreet[].class);
        return WebResult.OK(result);
    }

    /*
     * 登陆
     */
    @RequestMapping("/login")
    @ResponseBody
    public WebResult loginPost(HttpServletRequest request) {
        String loginName = request.getParameter("userName");
        String password = request.getParameter("passWord");
        String uuid = request.getParameter("uuid");

        // 判断楼长的用户名密码是否正确
        if ("admin".equals(loginName) && "123456".equals(password)) {
            return WebResult.OK();
        } else {
            return WebResult.FAIL("用户名或密码错误");
        }
    }
}
